# 分析录音
"""
读取每个录音文件 并绘制音频波形图，标记识别的鼾声波，并生成报告
"""


from multiprocessing import Pool, cpu_count, Manager,freeze_support
import librosa
import matplotlib.pyplot as plt
from utils.StandardTools import calculate_time
from utils.utils import printx
from colorama import Fore, Style
from scipy.signal import find_peaks
from config import *
import sys
from utils.utils import get_files_with_suffix,check_recod_path
from report import report_day,report_quqe_to_sqlite,report_sum
import init

import numpy as np


#60s波形图
@calculate_time
def creat_photo_60s(path,file_name,q):

    # 加载音频文件
    file_path = f'data/{path}/{file_name}'
    y, sr = librosa.load(file_path, dtype='float32',sr=RATE  ) #1184956416
    x = range(len(y))

    peaks, _ = find_peaks(y, height=height, distance=distance, prominence=prominence)
    #peaksdb = librosa.amplitude_to_db(np.abs(peaks), ref=np.max)

    len_peaks = len(peaks)
    stat = '存在异常数据' if len_peaks > (F+2) else ''
    color= 'red' if len_peaks > (F+2) else 'green' if len_peaks ==0 else 'black'

    q.put([file_name[6:-4],len_peaks])

    # 打印波峰
    printx(Fore.GREEN,("peaks:", len_peaks,"Peak:",y[peaks]))


    plt.switch_backend('Agg') # 设置Agg后端
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False  # 解决保存图像时负号'-'显示为方块的问题

    fig, ax = plt.subplots()
    fig.set_tight_layout(True)


    #ax.yaxis.set_ticklabels([]) # 隐藏默认的Y轴标签
    ax.set_ylim(-0.1, 0.1) # 设置Y轴的范围为[-1.0, 1.0]


    ax.plot(x,y)  # 示例数据

    if not stat:
        ax.scatter(peaks, y[peaks], color='#FFA500', zorder=1)  #  标记打鼾点
    else:
        ax.scatter(peaks, y[peaks], color='red', zorder=1)  # 标记异常点

    # 为每个点添加文字
    for xi, yi, label in zip(peaks, y[peaks], y[peaks]):
        ax.text(xi, yi, round(label,4), ha='center', va='bottom',rotation=45)  # ha: 水平对齐, va: 垂直对齐

    ax.text(0.05, 0.99, file_name[6:-4]+'\n'+str(len_peaks),
        transform=ax.transAxes,
        ha='left', va='top',
        fontsize=36,
        color=color
        )

    fig.set_size_inches(5, 5)  # 5英寸×5英寸
    fig.savefig(f'data/img_{path}/jpg_{file_name}.jpg', dpi=100, )  # 较低的dpi加快保存速度

    plt.close(fig)  # 显式关闭图形释放内存


def handle_result(result):
    """处理成功完成的任务"""
    #print(result,'aaa')
    pass


@calculate_time
def main(recod_path):
    q = Manager().Queue()
    if not recod_path:
        recod_path = check_recod_path(input("输入data目录下的录音文件夹的名称。例如recod_20250518_002139 \n："))
    list_files = get_files_with_suffix('data/' + recod_path, '.mp3')
    print(list_files)
    if not list_files:
        exit(f'{recod_path} 为空，退出')
    init.create_folder(f'data/img_{recod_path}')
    init.creat_clear_table_count(recod_path)


    p4 = Pool(cpu_count() - 2) if cpu_count() > 4 else Pool(cpu_count())
    for i in list_files[:]:
        p4.apply_async(creat_photo_60s, args=(recod_path, i, q), callback=handle_result)
    p4.close()
    p4.join()

    report_quqe_to_sqlite(q, recod_path)
    report_day(recod_path)
    report_sum()
    print("完成...")


if __name__ == '__main__':
    freeze_support()
    print("启动...")

    main(0)


